package com.sinba.common.system.service;

import com.sinba.common.dto.PageDTO;
import com.sinba.common.sms.HttpSender;
import com.sinba.common.system.dao.IActivationCodeDAO;
import com.sinba.common.system.dto.ActivationCodeDTO;
import com.sinba.common.system.dto.RuleDTO;
import com.sinba.common.system.entity.ActivationCode;
import com.sinba.common.user.dao.IRegisterUserDAO;
import com.sinba.common.user.entity.RegisterUser;
import com.sinba.common.util.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class ActivationCodeService
    implements IActivationCodeService
{
    @Autowired
    private IActivationCodeDAO activationCodeDAO;
    @Autowired
    private IEmailService emailService;
    @Autowired
    private IRegisterUserDAO registerUserDAO;
    @Autowired
	private IRuleService ruleService;

    @Transactional
    public void getEmailActivationCode(final ActivationCodeDTO dto )
    {
        ActivationCode entity = new ActivationCode(  );
        ActivationCodeDTO.dto2entity( dto, entity );
        entity.setCreateTime( new Date(  ) );
        //有效时间 +10分钟
        entity.setValidDate( new Date( entity.getCreateTime().getTime(  ) + ( 10 * 60 * 1000 ) ) );

        final String code = NextInt( 100000, 999999 ) + "";
        entity.setActivationCode( code );
        entity.setStatus(NOT_USE);//未使用
        activationCodeDAO.save( entity );

        if("Email".equals(dto.getType())){
        	  if ( ( dto.getAuthStr(  ) != null ) && ( dto.getAuthStr(  ).indexOf( "@" ) == -1 ) ) {
                  RegisterUser user = registerUserDAO.findUniqueBy( "loginName", dto.getAuthStr(  ) );
                  if ( user != null ) {
                      dto.setAuthStr( user.getEmail(  ) );
                  }
              }
              RuleDTO ruleDTO = ruleService.findRuleInfo();
              //发送邮件
              String title = ruleDTO.getRule006();
              String content = ruleDTO.getRule007().replace("${code}", code);
              if("ChangeInfo".equals(dto.getCategory()) || "UpdatePassword".equals(dto.getCategory()) || "FindPassword".equals(dto.getCategory())){
            	  title ="账户正在修改资料、密码和找回密码操作验证码-ZOPA";
            	  content = "CHINA-ZOPA（中国版）提示：您的账户正在修改资料、密码和找回密码操作。如非本人操作，请通过系统“站内通信”联系管理员！您的本次操作验证码是："+code;
              }else if(dto.getCategory().indexOf("_EN")>-1){
            	  title = "Account codes are operating -ZOPA";
            	  content = "ZOPA remind:Your account is being modified. Non self operation，Please contact the administrator through the platform！Verification code is："+code;
              }
              final String title1 = title;
              final String content1 = content;
              new Thread(new Runnable() {
      			public void run() {
      				emailService.sendMail( dto.getAuthStr(  ), title1, content1 );
      			}
      		}).start();
        }else if("Mobile".equals(dto.getType())){
        	String msg ="您的手机验证码为："+code+"，该验证码10分钟内有效。如非本人操作，请尽快联系客服处理。";
        	String mobile =dto.getAuthStr();
        	RegisterUser user = registerUserDAO.findUniqueBy( "loginName", dto.getAuthStr());
        	if(user!=null){
        		System.out.println("-----将验证码"+code+"发送到手机号:"+user.getMobile());
        		if(StringUtils.hasText(user.getMobile())){
        			mobile = user.getMobile();
        		}
        	}
        	
        	HttpSender.sendSms(mobile, msg);
        	
        }
        
      
    }

    public int NextInt( final int min, final int max )
    {
        Random rand = new Random(  );
        int tmp = Math.abs( rand.nextInt(  ) );

        return ( tmp % ( max - min + 1 ) ) + min;
    }

    @Transactional
    public boolean authEmailCode( ActivationCodeDTO dto )
    {
    	// TODO Auto-generated method stub
    	RuleDTO ruleDTO = ruleService.findRuleInfo();
    	if(ruleDTO.isRule022()){
    		List<ActivationCode> acs = activationCodeDAO.findActivationCode( dto );
            if ( acs.size(  ) > 0 )
            {
                return true;
            } else{
                return false;
            }
    	}else{
    		return true;
    	}
    }

    @Transactional
    public PageDTO emailAuthPages( ActivationCodeDTO activationCodeDTO, String sord, String sidx )
    {
        PageDTO pagedto = activationCodeDAO.emailAuthPages( activationCodeDTO, sord, sidx );
        List<ActivationCode> list = (List<ActivationCode>) pagedto.getData(  );
        List<ActivationCodeDTO> orderDtos = new ArrayList<ActivationCodeDTO>(  );

        for ( ActivationCode entity : list )
        {
            ActivationCodeDTO dto = new ActivationCodeDTO(  );
            ActivationCodeDTO.entity2dto( entity, dto );
            orderDtos.add( dto );
        }

        pagedto.setData( orderDtos );

        return pagedto;
    }

    public void deleteActivationCode( Long[] ids )
    {
        activationCodeDAO.deleteByIds( ids );
    }
    
    /**
     * 验证码验证是否有效
     * @param authStr
     * @param code
     * @param type
     * @return
     */
    @Transactional
    public ActivationCode authVerificationCode(String authStr ,String code ,String category){
    	
  /*  	//路过验证
    	ActivationCode ac1 = new ActivationCode();
    	ac1.setId(1L);
    	ac1.setAuthStr("");
    	ac1.setStatus("未使用");
    	return ac1;*/
    	
    	if (!StringUtils.hasText(authStr)) {
			return null;
		}
    	ActivationCode ac = activationCodeDAO.getCodeByAuthStrAndType(authStr,code,category);
    	if(ac==null){
    		return null;
    	}else{
    		if(new Date().before( ac.getValidDate() )){//在有限其内
    			return ac;
    		}else{
    			return null;
    		}
    	}
    }
    
}
